﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NFlickr.Communication;
using NFlickr.Factory;
using NFlickr.Core.Interface;
using System.Xml.Linq;

namespace NFlickr.Core
{
    public class Frob : RequireSignedServiceBase
    {

        internal Frob()
        {

        }

        private string _value;
        public string Value
        {
            get
            {
                if (string.IsNullOrEmpty(_value))
                {
                    if (Refresh())
                    {
                        return _value;
                    }
                    else
                    {
                        return null;
                    }
                }
                return _value;
            }
        }

        public override string MethodName
        {
            get { return "flickr.auth.getFrob"; }
        }

        public override string TagName
        {
            get { return "frob"; }
        }

        public override bool Refresh()
        {
            IChannel channel = FlickrChannelFactory.CreateInstance();

            channel.Complete +=new EventHandler<SendRequestCompletedEventArgs>(channel_Complete);
            channel.SignatureRequired += new NFlickr.Core.Interface.SignatureRequiredEventHandler(channel_SignatureRequired);
            

            Params = new Dictionary<string, string>();

            Params.Add(NFlickr.Resource.FlickrService.ApplicationKeyName,ApplicationKey);
            Params.Add(NFlickr.Resource.FlickrService.MethodKeyName, MethodName);
            
            IResult result = channel.SendRequest(FlickrServiceUrl, this);

            if (result != null && result.ResultCode == 0)
            {
                _value = result.ResultString;
                return true;
            }
            return false;
        }

        string channel_SignatureRequired(object sender, NFlickr.Core.Interface.SignatureRequiredEventArgs args)
        {
            Params.Add(NFlickr.Resource.FlickrService.SignatureKeyName, args.Singnature);
            return GetQueryString(Params);
        }

        void channel_Complete(object sender, NFlickr.Core.Interface.SendRequestCompletedEventArgs args)
        {

            args.Result = ParseResult(args.Response);
        }
    }
}
